package com.gqzmy.springboot3.config;

import com.gqzmy.springboot3.mapper.base.TableBase;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.SimpleIdGenerator;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author 周小哥  gqzmy@163.com 2023/4/24 14:51
 */

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MyBatisMetaInterceptor implements Interceptor {

    public static final Logger logger = LoggerFactory.getLogger(MyBatisMetaInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object parameter = args[1];
        if (Objects.isNull(parameter)) {
            return invocation.proceed();
        }
        MappedStatement mappedStatement = (MappedStatement) args[0];
        String id = mappedStatement.getId();
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

        List<Field> fieldList = new ArrayList<>();
        getFields(parameter, fieldList, null);
        for (Field field : fieldList) {

            MybatisId mybatisId = field.getAnnotation(MybatisId.class);
            if (Objects.nonNull(mybatisId)) {
                if (SqlCommandType.INSERT == sqlCommandType) {
                    MybatisId.IdType type = mybatisId.type();
                    if (type == MybatisId.IdType.ID_TYPE_UUID) {
                        field.setAccessible(true);
                        Object o = field.get(parameter);
                        field.setAccessible(false);
                        if (Objects.isNull(o) || Objects.equals(o, "")) {
                            field.setAccessible(true);
                            SimpleIdGenerator simpleIdGenerator = new SimpleIdGenerator();
                            field.set(parameter, simpleIdGenerator.generateId().toString());
                            field.setAccessible(false);
                        }
                    }
                }
            }

            MybatisCreateTime mybatisCreateTime = field.getAnnotation(MybatisCreateTime.class);
            if (Objects.nonNull(mybatisCreateTime)) {
                if (SqlCommandType.INSERT == sqlCommandType) {
                    String format = mybatisCreateTime.format();
                    if (StringUtils.hasText(format)) {
                        logger.warn("指定了时间格式{},该功能还未实现,哈哈~~~", format);
                        field.setAccessible(true);
                        Object o = field.get(parameter);
                        field.setAccessible(false);
                        if (Objects.isNull(o) || Objects.equals(o, "")) {
                            field.setAccessible(true);
                            field.set(parameter, LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
                            field.setAccessible(false);
                        }
                    } else {
                        field.setAccessible(true);
                        Object o = field.get(parameter);
                        field.setAccessible(false);
                        if (Objects.isNull(o) || Objects.equals(o, "")) {
                            field.setAccessible(true);
                            field.set(parameter, LocalDateTime.now());
                            field.setAccessible(false);
                        }
                    }
                }
            }

        }
        return invocation.proceed();
    }


    private void getFields(Object parameter, List<Field> fieldList, Class<?> superClass) {
        Class<?> aClass = superClass == null ? parameter.getClass() : superClass;
        if (Objects.nonNull(aClass)) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(aClass.getDeclaredFields())));
            if (aClass.getSuperclass() != null) {
                if (Objects.deepEquals(aClass.getSuperclass().getName(), TableBase.class.getName())) {
                    getFields(aClass.getSuperclass(), fieldList, aClass.getSuperclass());
                }
            }
        }
    }
}
